<template>
  <el-cascader
    v-model="inputValue"
    :style="{ width: width ? `${width}px` : '100%' }"
    :options="treeData"
    :show-all-levels="true"
    :clearable="true"
    :props="replaceFields"
    :disabled="disabled"
    :placeholder="searchPlaceholder"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
import { toArrayTree } from "xe-utils";
import { projectProjectAttachmentDirectoryList } from "@/api/pre-project-attachment";
export default {
  /**
   * 【文档目录】树选择组件，单选
   */
  name: "DirectoryTreeSingle",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    // 占位符
    placeholder: {
      type: String,
      default: "",
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 宽度，默认100%
    width: {
      type: Number,
      default: 200,
    },
    // 参考值：字典-文件类型 attachmentType
    projectType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // treeData 中对应的字段
      replaceFields: {
        children: "children",
        label: "directoryName",
        key: "id",
        value: "id",
      },
      // 数据源
      treeData: [],
      dropdownStyle: {
        zIndex: 3000,
      },
      tableData: [],
    };
  },
  computed: {
    searchPlaceholder: {
      get() {
        return this.placeholder ? `请选择${this.placeholder}` : `请选择`;
      },
      set() {},
    },
    inputValue: {
      get() {
        return this.value ? this.value : [];
      },
      set(val) {},
    },
  },
  created() {
    // 加载文档目录
    const params = {
      projectType: this.projectType,
    };
    projectProjectAttachmentDirectoryList(params).then((res) => {
      this.tableData = res || [];
      const data = toArrayTree(res);
      this.treeData = this.filterNull(data);
      console.log("treeData", this.treeData);
    });
  },
  methods: {
    filterNull(data) {
      return data.map((item) => {
        if (item.children && item.children.length) {
          this.filterNull(item.children);
        } else {
          delete item.children;
        }
        return item;
      });
    },
    handleChange(value) {
      if (value) {
        const id = value[value.length - 1];
        const item = this.tableData.find((v) => {
          return v.id === id;
        });
        this.$emit("change", id, item.directoryName);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
